package com.xuan.contest.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xuan.contest.common.cache.CacheFactory;
import com.xuan.contest.common.job.CheckAnswerJob;
import com.xuan.contest.common.job.ExecuteJob;
import com.xuan.contest.common.utils.ContestStatusEnum;
import com.xuan.contest.common.utils.SpringContextHolder;
import com.xuan.contest.common.utils.Utils;
import com.xuan.contest.dao.ContestMapper;
import com.xuan.contest.entry.ContestEntity;
import com.xuan.contest.entry.UserAnswerEntity;
import com.xuan.contest.service.IConTestService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Calendar;
import java.util.Queue;

/**
 * @author XinZhaoXuan
 * @date 2018/9/7
 */
@Service
public class ContestServiceImpl extends ServiceImpl<ContestMapper, ContestEntity> implements IConTestService {

    Logger logger = LoggerFactory.getLogger(ContestServiceImpl.class);

    @Autowired
    private ContestMapper contestMapper;

    /**
     * @param entity
     */
    @Override
    public void answer(UserAnswerEntity entity) {

        CacheFactory.redisCache().setCacheQueueData(CacheFactory.QUEUE_ANSWER, entity);
        //queue.offer(entity);
    }

    @Override
    public Queue<UserAnswerEntity> getQueue() {
        return null;
    }

    @Override
    public void approvalContest(Integer id) {
        ExecuteJob schedulerAllJob = SpringContextHolder.getBean("executeJob");
        ContestEntity contestEntity = contestMapper.selectById(id);
        Assert.isTrue(contestEntity.getEndTime().compareTo(Calendar.getInstance().getTime()) >= 0, "考试结束时间错误");

        try {
            schedulerAllJob.startJob(CheckAnswerJob.class, Utils.getCron(contestEntity.getEndTime()));
            contestEntity.setStatus(ContestStatusEnum.RUNING.getValue());
            contestEntity.updateById();

            CacheFactory.redisCache().setCacheObject(CacheFactory.CONTEST_RUNNING, id);
        } catch (SchedulerException e) {
            e.printStackTrace();
            logger.error("执行 处理 答题 job 失败");
        }
    }
}
